package com.hqd.ch03.v15.beans.support;

import com.hqd.ch03.v15.beans.TypeConverter;
import com.hqd.ch03.v15.beans.property.support.PropertyEditorRegistrySupport;

import java.beans.PropertyEditor;

public class TypeConverterSupport extends PropertyEditorRegistrySupport implements TypeConverter {
    @Override
    public <T> T convertIfNecessary(Object value, Class<T> requiredType) {
        PropertyEditor editor = findCustomEditor(requiredType);
        if (editor == null) {
            editor = getDefaultEditor(requiredType);
        }
        if (editor == null) {
            return (T) value;
        }
        if (value instanceof String) {
            editor.setAsText((String) value);
        } else {
            editor.setValue(value);
        }
        return (T) editor.getValue();
    }
}
